/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.interaction.weixin;

import java.security.MessageDigest;
import java.util.Arrays;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

/**
 *
 * @author lethe
 */
public class MainModule {

    @At("/signature")
    @Ok("raw")
    public String doSignature(@Param("signature")String signature,@Param("timestamp")String timestamp,@Param("nonce")String nonce,@Param("echostr")String echostr)
    {
        String[] strs={"interaction",timestamp,nonce};
        Arrays.sort(strs);
        String sign=Arrays.toString(strs);
        
        String result="";
        
        MessageDigest md=null;
        try{
            md=MessageDigest.getInstance("SHA-1");
            byte[] digest=md.digest(sign.getBytes());
            sign=bytetoString(digest);
            if(signature!=null && signature.trim().equalsIgnoreCase(sign))
            {
                result=echostr;
            }
            else
            {
                result="error";
            }
        }
        finally
        {
            return result;
        }
    }
    
    public static String bytetoString(byte[] digest) {
        String str = "";
        String tempStr = "";
        
        for (int i = 1; i < digest.length; i++) {
            tempStr = (Integer.toHexString(digest[i] & 0xff));
            if (tempStr.length() == 1) {
                str = str + "0" + tempStr;
            }
            else {
                str = str + tempStr;
            }
        }
        return str.toLowerCase();
    }
}
